package com.lingyun.financialmanagement.utils;

import com.lingyun.financialmanagement.dao.mapper.UsersMapper;
import com.lingyun.financialmanagement.dao.pojo.Users;
import com.lingyun.financialmanagement.vo.ErrorCode;
import com.lingyun.financialmanagement.vo.Result;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.data.redis.core.RedisTemplate;

public class TokenGetUser {
    public static Result getAccount(HttpServletRequest request, RedisTemplate<String, String> redisTemplate, String tokenAccountPrefix) {
        String token = request.getHeader("token");
        String account = redisTemplate.opsForValue().get(tokenAccountPrefix + token);
        if (account == null) {
            return Result.fail(ErrorCode.TOKEN_ERROR.getCode(), ErrorCode.TOKEN_ERROR.getMsg());
        }
        return Result.success(account);
    }

    public static Result getUsers(HttpServletRequest request, RedisTemplate<String, String> redisTemplate, String tokenAccountPrefix, UsersMapper usersMapper) {
        String token = request.getHeader("token");
        String account = redisTemplate.opsForValue().get(tokenAccountPrefix + token);
        if (account == null) {
            return Result.fail(ErrorCode.TOKEN_ERROR.getCode(), ErrorCode.TOKEN_ERROR.getMsg());
        }

        Users users = usersMapper.selectByAccount(account);
        if (users == null) {
            return Result.fail(ErrorCode.USERS_NULL.getCode(), ErrorCode.USERS_NULL.getMsg());
        }
        return Result.success(users);
    }
}
